import unittest

from tinydb.catalog.index import *
from tinydb.catalog.basic import *
from tinydb.catalog.database import *
from tinydb.catalog.entry import *
from tinydb.catalog.function import *
from tinydb.catalog.table import *
from tinydb.constant import CATALOG_DIRECTORY

def clear_catalog_temp():
    # 删除测试目录
    for filename in os.listdir(CATALOG_DIRECTORY):
        file_path = os.path.join(CATALOG_DIRECTORY, filename)
        try:
            if os.path.isfile(file_path) or os.path.islink(file_path):
                os.unlink(file_path)
            elif os.path.isdir(file_path):
                os.rmdir(file_path)
        except Exception as e:
            print('Failed to delete %s. Reason: %s' % (file_path, e))

class TestCatalog(unittest.TestCase):
    def setUp(self):
        clear_catalog_temp()
        
    def tearDown(self):
        clear_catalog_temp()

    def test_catalog_table(self):
        catalog_table = CatalogTable()

        catalog_table.insert(CatalogTableFrom('t1', ['id', 'name'], [int, str]))
        catalog_table.insert(CatalogTableFrom('t2', ['id', 'name', 'address'], [int, str, str]))
        catalog_table.insert(CatalogTableFrom('t3', ['id', 'city', 'area'], [int, str, str]))
        catalog_table.insert(CatalogTableFrom('t4', ['id', 'company', 'job'], [int, str, str]))

        catalog_table.dump()

        # 模拟数据库的catalog重新加载过程
        catalog_table2 = CatalogTable()
        catalog_table2.load()

        excepted = """[CREATE TABLE t1 (id int, name str);, CREATE TABLE t2 (id int, name str, address str);, CREATE TABLE t3 (id int, city str, area str);, CREATE TABLE t4 (id int, company str, job str);]"""
        self.assertEqual(str(catalog_table2.rows), excepted)

    def test_catalog_index(self):
        catalog_index = CatalogIndex()
        catalog_index.insert(CatalogIndexFrom('idx', ['id'], 't1'))

        catalog_index.dump()

        # 模拟数据库的catalog重新加载过程
        catalog_index2 = CatalogIndex()
        catalog_index2.load()

        excepted = """[CREATE INDEX idx ON t1 (id);]"""
        self.assertEqual(str(catalog_index2.rows), excepted)



if __name__ == '__main__':
    unittest.main()
